<template>
  <quill-editor
    ref="quillRef"
    :content="content"
    :options="editorOption"
    class="editor"
    contentType="html"
    style="height: 300px"
    @update:content="onEditorChange()"
  />
</template>

<script setup>
import {Quill, QuillEditor} from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import Compressor from 'compressorjs';
import config from "../../config.js";


Quill.register("modules/imageUploader", ImageUploader);

const props = defineProps(['control', 'placeholder', 'value']);
const emit = defineEmits(['update:value']);
const control = props.control
const content = props.value ? props.value : ref("<P></P>")
const quillRef = ref(null)

let editorOption = {
  placeholder: "请输入活动文本......",
  theme: "snow",
  modules: {
    clipboard: {
      matchVisual: false, // 禁用从剪贴板中粘贴图片
    },
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
      [{color: []}, {background: []}], // 字体颜色、字体背景颜色
      [{align: []}], // 对齐方式
      [{size: ['small', false, 'large', 'huge']}], // 字体大小
      [{font: []}], // 字体种类
      [{header: [1, 2, 3, 4, 5, 6, false]}], // 标题
      [{direction: 'ltl'}], // 文本方向
      [{direction: 'rtl'}], // 文本方向
      [{indent: '-1'}, {indent: '+1'}], // 缩进
      [{list: 'ordered'}, {list: 'bullet'}], // 有序、无序列表
      [{script: 'sub'}, {script: 'super'}], // 上标/下标
      ['blockquote', 'code-block'], // 引用  代码块
      ['clean'], // 清除文本格式
      ['link', 'image'], // 链接、图片
    ],
    // 上传图片
    imageUploader: {
      upload: async (file) => {
        try {
          const compressedFile = await compressImage(file); // 压缩图片
          return new Promise((resolve, reject) => {
            const formData = new FormData();
            formData.append("file", compressedFile);
            const {data, isFinished, error} = useApi({
              method: 'POST',
              url: '/base/file/upload',
              dataType: 'file',
              data: formData,
              showError: false
            });

            watchEffect(() => {
              if (isFinished.value) {
                if (error.value != null) {
                  return;
                }
                const {url} = data.value;
                const path = config.files.resolve(url);
                resolve(path)

              }
            });
          })
        } catch (error) {
          console.error('上传图像时出错:', error);
        }
      }
    },
  },
};


// 图片压缩
const compressImage = (file) => {
  return new Promise((resolve, reject) => {
    new Compressor(file, {
      quality: 0.6, // 设置压缩质量
      maxWidth: control?.config?.maxWidth ? control?.config?.maxWidth : 400, // 设置图片最大宽度
      maxHeight: control?.config?.maxHeight ? control?.config?.maxHeight : 400, // 设置图片最大高度
      mimeType: file.type,
      success(result) {
        // 压缩后的图像数据封装在 Blob 中
        // 将 Blob 数据转换为 File 对象
        const fileName = file.name;
        const compressedFile = new File([result], fileName, {type: result.type});
        resolve(compressedFile);
      },
      error(error) {
        reject(error);
      },
    });
  });
}

const onEditorChange = async () => {
  const text = toRaw(quillRef.value).getHTML()
  emit('update:value', text);
}

</script>
